import os
from pathlib import Path
from dotenv import load_dotenv, set_key, dotenv_values

load_dotenv()

'''
Support list:
1. int
2. bool
3. float
4. str
'''

class GlobalContextData:
    CORS = True
    Host = 'localhost'
    Port = 5000

    Debug = True
    HotLoad = True

    DataBaseConnectionString = 'sqlite+pysqlite:///.db'

    ProductName = 'Demo'
    LogPath = Path.cwd() / 'logs' / 'Demo.log'
    LogManageUsername = 'log'
    LogManagePassword = 'password'

    CacheDir = Path.cwd() / '.cache'


# Load existing environment variables
env_path = Path.cwd() / '.env'

# Check if the .env file exists, if not, create it
if not env_path.exists():
    env_path.touch()

existing_env = dotenv_values(str(env_path))

def convert_to_type(_value, _desired_type):
    if _desired_type is bool:
        # Convert to boolean with an explicit check
        if _value.lower() in ('true', '1', 'yes'):
            return True
        elif _value.lower() in ('false', '0', 'no'):
            return False
        else:
            raise ValueError(f"Cannot convert {_value} to a boolean _value.")
    else:
        # Use the _desired_type constructor for other types
        return _desired_type(_value)


# Iterate over attributes, setting defaults and types
for attribute, default_value in [(key, value) for key, value in GlobalContextData.__dict__.items() if '__' not in key]:
    desired_type = type(default_value)

    if attribute not in existing_env:
        set_key(str(env_path), attribute, str(default_value))

    # Retrieve the value, with a fallback to default
    value = os.getenv(attribute, default_value)

    try:
        # Attempt to set the attribute with proper typing
        setattr(GlobalContextData, attribute, convert_to_type(value, desired_type))
    except Exception as e:
        print(f'** startup config.py - Load Global "{attribute}" failed, '
              f'set {value} to a {desired_type} value: {e}')
